package com.zb.util;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zb.utils.RandomUtil;
import com.zb.yaml.FilePath;
import lombok.extern.log4j.Log4j2;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 文件上传工具类
 * @Author WEN
 * @Date 2023/8/11 0011
 **/
@Log4j2
public class FileUploadUtil {
    private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM");

    /**
     * 上传附件
     * @param customerAnnexCode 企业附件编码
     * @param folder 文件夹
     * @param file 文件对象
     * @return
     */
    public static String uploadAnnexFile(String uploadPath, String annexVisitPath, String customerAnnexCode, String folder, MultipartFile file) {
        if (null == file) {
            return "";
        }
        List<MultipartFile> fileList = new ArrayList<>();
        fileList.add(file);
        List<String> annexList = uploadAnnexFile(uploadPath, annexVisitPath, customerAnnexCode, folder, fileList);
        return annexList.isEmpty()? "" : annexList.get(0);
    }

    /**
     * 上传附件
     * @param customerAnnexCode 企业附件编码
     * @param folder 文件夹
     * @param fileList 文件对象
     */
    public static List<String> uploadAnnexFile(String uploadPath, String annexVisitPath, String customerAnnexCode, String folder, List<MultipartFile> fileList) {
        log.info("工单附件:{}", fileList);
        if (CollectionUtil.isEmpty(fileList)) {
            Assert.isTrue(false, "附件列表为空");
        }
        List<String> annexList = new ArrayList<>();
        folder = folder + "/" + SDF.format(new Date());
        log.info("folder59:{}", folder);
        // 文件存储路径，且拼接文件名
        String filePath = null;
        File dest = null;
        String fileName = "";
        int index = 0 ;
        for (MultipartFile file : fileList) {
            index = file.getOriginalFilename().lastIndexOf(".");
            log.info("index67:{}", index);
            if (index !=  -1) {
                fileName = file.getOriginalFilename().substring(0, index) + "_" + RandomUtil.dateRandom() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") -1);
                log.info("fileName70:{}", fileName);
            } else {
                fileName = file.getOriginalFilename() + "_" + RandomUtil.dateRandom() + ".png";
                log.info("fileName73:{}", fileName);
            }
//            Objects.requireNonNull(file.getOriginalFilename()).substring(0, file.getOriginalFilename().lastIndexOf(".")) + "_" + RandomUtil.dateRandom() + Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf(".") -1)
            filePath = customerAnnexCode + "/" + folder + "/" + fileName;
            log.info("filePath77:{}", filePath);
//            dest = new File(FilePath.annexUploadPath() + filePath);
            dest = new File(uploadPath + filePath);
            log.info("dest80:{}", dest);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
                log.info("dest83:{}", dest);
            }
            try {
                file.transferTo(dest);
//                annexList.add(FilePath.domain() + FilePath.annexVisitPath() + filePath);
                annexList.add(annexVisitPath + filePath);
            } catch (IOException e) {
                log.error("文件上传异常：", e);
            }
            log.info("annexList92:{}", annexList);
        }
        return annexList;
    }

    /**
     * 上传视频
     * @param customerVideoCode 企业视频编码
     * @param folder 文件夹
     * @param fileList 文件对象
     */
    public static List<String> uploadVideoFile(String videoUploadPath, String videoVisitPath, String customerVideoCode, String folder, List<MultipartFile> fileList) {
        if (CollectionUtil.isEmpty(fileList)) {
            return new ArrayList<>();
        }
        List<String> annexList = new ArrayList<>();
        folder = folder + "/" + SDF.format(new Date());
        // 文件存储路径，且拼接文件名
        String filePath = "";
        File dest = null;
        String fileName = "";
        int index = 0 ;
        for (MultipartFile file : fileList) {
            index = file.getOriginalFilename().lastIndexOf(".");
            if (index !=  -1) {
                fileName = file.getOriginalFilename().substring(0, index) + "_" + RandomUtil.dateRandom() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") -1);
            } else {
                fileName = file.getOriginalFilename() + "_" + RandomUtil.dateRandom() + ".mp4";
            }
//            Objects.requireNonNull(file.getOriginalFilename()).substring(0, file.getOriginalFilename().lastIndexOf(".")) + "_" + RandomUtil.dateRandom() + Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf(".") -1)
            filePath = customerVideoCode + "/" + folder + "/" + fileName;
//            dest = new File(FilePath.videoUploadPath() + filePath);
            dest = new File(videoUploadPath + filePath);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
//                annexList.add(FilePath.domain() + FilePath.videoVisitPath() + filePath);
                annexList.add(videoVisitPath + filePath);
            } catch (IOException e) {
                log.error("文件上传异常：", e);
            }
        }
        return annexList;
    }


    /**
     * 批量删除附件
     * @param pathList
     */
    public static void deleteFileBatchByPath(String domain, String annexVisitPath, String videoVisitPath, List<String> pathList) {
        if (CollectionUtil.isEmpty(pathList)) {
            return;
        }
        for (String path : pathList) {
            if (StringUtils.isBlank(path)) {
                continue;
            }
//            path = path.contains(FilePath.domain())? path.replace(FilePath.domain(), "") : path;
            path = path.contains(domain)? path.replace(domain, "") : path;
            // 删除附件
            if (path.contains(annexVisitPath)) {
//            if (path.contains(FilePath.annexVisitPath())) {
                path = path.replace(annexVisitPath, "");
//                deleteFile(FilePath.annexUploadPath() + path);
                deleteFile(annexVisitPath + path);
                continue;
            }
            // 删除视频文件
            if (path.contains(videoVisitPath)) {
//            if (path.contains(FilePath.videoUploadPath())) {
                path = path.replace(videoVisitPath, "");
//                deleteFile(FilePath.videoUploadPath() + path);
                deleteFile(videoVisitPath + path);
            }
        }
    }


    /**
     * 删除文件
     * @param path
     */
    private static void deleteFile(String path) {
        try {
            boolean result = FileSystemUtils.deleteRecursively(new File(path));
            log.info("文件删除结果：{}", result);
        }catch (Exception e) {
            log.error("文件删除失败：{}", path);
        }
    }
}
